有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

反射如何检查java。朗。反思。方法返回类型是集合?

我有一个方法可以得到如下所示的bean属性列表。如何检查方法返回类型是否为集合(如List、Set…)。iInstance(Collection.class)不起作用

public static List<String> getBeanProperties(String className, boolean withLists) {

    ArrayList<String> a = new ArrayList();
    try {
        Class c = Class.forName(className);
        Method methods[] = c.getMethods();
        for (int i = 0; i < methods.length; i++) {
            String m = methods[i].getName();
            if(m.startsWith("get") && methods[i].getParameterTypes().length == 0) {

                if((methods[i].getReturnType().isInstance(Collection.class)) && !withLists) {
                    // skip lists
                } else {
                    String f = m.substring(3);
                    char ch = f.charAt(0);
                    char lower = Character.toLowerCase(ch);
                    f = lower + f.substring(1);
                    a.add(f);
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return a;
}

共 (2) 个答案

  1. # 1 楼答案

    使用Collection.class.isAssignableFrom(returnType)Reference

  2. # 2 楼答案

    Method#getReturnType返回单个类对象,即与方法声明相对应的类对象。如果该方法被声明为返回一个Collection,您将看到一个集合。如果声明返回CollectionList', ..), you'll need to check, if)的子类,则集合`可从实际返回类型赋值:

     Class<?> realClass = methods[i].getReturnType(); // this is a real class / implementation
     if (Collection.isAssignableFrom(realClass)) {
        // skip collections (sic!)
     }